<?php
namespace App\Services\WxMass\Factory;

use App\Facades\EasyWechat;
use App\Models\WxMass;
use App\Models\WxMassArticle;
use App\Models\WxMassResult;
use App\Services\WxCommon\WxError;
use App\Services\WxMaterial\WxMaterialService;

/**
 * 图文群发业务逻辑
 * @package App\Services\WxMass
 */
class WxMassNews extends WxMassAbstract
{
    /**
     * 构造函数
     */
    public function __construct($appid = '')
    {
        parent::__construct($appid);

        $this->msgName = '图文';
    }

    /**
     * 发送处理
     * @param $massId
     */
    public function handleSend($massId)
    {
        \DB::beginTransaction();
        try{
            $massData = WxMass::with('material')->where('appid', $this->appid)->where('is_open', 1)->where('is_send', 0)->findOrFail($massId);
            if (empty($massData->push_time) || strtotime($massData->push_time) <= time()){
                $mediaId = (new WxMaterialService($this->appid))->createMaterial($massData->msg_type)->getMediaId($massData->material_id);
                $message = new \EasyWeChat\Kernel\Messages\Media($mediaId, 'mpnews');
                try{
                    $apiRs = $this->sendMass($message, $massData->filter_rule);
                    $massData->errcode = $apiRs['errcode'] ?? 0;
                    $massData->errmsg = $apiRs['errmsg'] ?? '';
                    $massData->msg_id = $apiRs['msg_id'] ?? 0;
                    $massData->msg_data_id = $apiRs['msg_data_id'] ?? 0;
                }catch (\Exception $e){
                    $massData->errcode = 1;
                    $massData->errmsg = $e->getMessage();
                }
                $massData->is_send = 1;
                $massData->save();
                //保存群发对应文章
                if (!empty($massData->msg_id) && !empty($massData->material->news)){
                    foreach ($massData->material->news as $index => $new){
                        WxMassArticle::updateOrCreate(
                            [
                                'appid' => $this->appid,
                                'msg_id' => $massData->msg_id,
                                'index_num' => $new->order_num ?? 0,
                            ],
                            [
                                'mass_id' => $massData->mass_id,
                                'msg_data_id' => $massData->msg_data_id ?? 0,
                                'new_id' => $new->new_id,
                                'title' => $new->title,
                                'open_comment' => $new->need_open_comment,
                            ]
                        );
                    }
                }
            }

            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        return true;
    }

    /**
     * 回调消息处理
     * @param $eventData
     */
    public function handleCallback($eventData)
    {
        \DB::beginTransaction();
        try {
            $msgId = $eventData['MsgID'] ?? 0;
            if ($msgId){
                WxMassResult::updateOrCreate(
                    ['appid'=>$this->appid, 'msg_id'=>$msgId],
                    [
                        'status' => $eventData['Status'] ?? 0,
                        'total_count' => $eventData['TotalCount'] ?? 0,
                        'filter_count' => $eventData['FilterCount'] ?? 0,
                        'sent_count' => $eventData['SentCount'] ?? 0,
                        'error_count' => $eventData['ErrorCount'] ?? 0,
                        'check_state' => $eventData['CopyrightCheckResult']['CheckState'] ?? 0,
                    ]
                );
            }
            if (!empty($eventData['CopyrightCheckResult']['ResultList']['item'])){
                foreach ($eventData['CopyrightCheckResult']['ResultList']['item'] as $item){
                    WxMassArticle::updateOrCreate(
                        [
                            'appid' => $this->appid,
                            'msg_id' => $msgId,
                            'index_num' => !empty($item['ArticleIdx']) ? $item['ArticleIdx'] -1 : 0,//推送结果的文章序号从1开始
                        ],
                        [
                            'user_declare_state' => $item['UserDeclareState'] ?? 0,
                            'audit_state' => $item['AuditState'] ?? 0,
                            'original_article_url' => $item['OriginalArticleUrl'] ?? '',
                            'original_article_type' => $item['OriginalArticleType'] ?? 0,
                            'can_reprint' => $item['CanReprint'] ?? 0,
                            'need_replace_content' => $item['NeedReplaceContent'] ?? 0,
                            'need_show_reprint_source' => $item['NeedShowReprintSource'] ?? 0,
                        ]
                    );
                }
            }
            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        return true;
    }

    /**
     * 群发预览
     * @param $massId
     * @param $to
     * @param string $previewType
     * @return bool
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     */
    public function preview($massId, $to, $previewType = 'touser')
    {
        $massData = WxMass::where('appid', $this->appid)->where('msg_id', 0)->findOrFail($massId);
        $app = EasyWechat::officialAccount($this->appid);
        $mediaId = (new WxMaterialService($this->appid))->createMaterial($massData->msg_type)->getMediaId($massData->material_id);
        if ($previewType == 'touser'){
            $apiRs = $app->broadcasting->previewNews($mediaId, $to);
        }elseif ($previewType == 'wxname'){
            $apiRs = $app->broadcasting->previewNews($mediaId, $to, $app->broadcasting::PREVIEW_BY_NAME);
        }
        WxError::checkApiResponse($apiRs);
        return true;
    }
}